<template>
  <div class="table-page">
    <a-space size="large" class="btn_wrap mb-20">
      <dl class="h-10n flex-center text-size-16 font-bold px-12 flex dl_1">
        <dt>源头群数：</dt>
        <dd>{{ userCount.sourceChatRoomNum }}</dd>
      </dl>
      <dl class="h-10n flex-center text-size-16 font-bold px-12 flex dl_2">
        <dt>启用源头群数：</dt>
        <dd>{{ userCount.sourceChatRoomEnablesNum }}</dd>
      </dl>
      <dl class="h-10n flex-center text-size-16 font-bold px-12 flex dl_3">
        <dt>关闭源头群数：</dt>
        <dd>{{ userCount.sourceChatRoomClosedNum }}</dd>
      </dl>
    </a-space>
    <a-form label-align="right" layout="inline" auto-label-width :model="listParams" size="small" class="form my-10">
      <a-form-item label="群状态" field="enabled" :show-colon="true">
        <a-select v-model="listParams.enabled" placeholder="全部">
          <a-option :value="''">全部</a-option>
          <a-option :value="1">开启</a-option>
          <a-option :value="0">关闭</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="推送状态" field="isPush" :show-colon="true">
        <a-select v-model="listParams.isPush" placeholder="全部">
          <a-option :value="''">全部</a-option>
          <a-option :value="1">开启</a-option>
          <a-option :value="0">关闭</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="" field="name">
        <a-input v-model="listParams.name" placeholder="请输入微信群名称">
          <template #prefix> <icon-search /> </template
        ></a-input>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" size="small" @click="changeCurrent(1)">
            <template #icon>
              <icon-search />
            </template>

            <template #default> 查询 </template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>

            <template #default> 重置 </template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <GiTable
      row-key="id"
      id="groupList"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <template #custom-extra>
        <a-space>
          <a-button type="primary" size="small" @click="onAddOrEdit(false)">
            <template #icon><icon-plus /> </template>
            <span>新增</span>
          </a-button>
        </a-space>
      </template>

      <template #isPush="{ record }">
        <a-switch
          :checked-value="true"
          checked-text="是"
          :unchecked-value="false"
          unchecked-text="否"
          v-model="record.isPush"
          :before-change="handleChangeStatus.bind(null, record, 'isPush')"
        >
        </a-switch>
      </template>
      <template #isDelay="{ record }">
        <a-switch
          :checked-value="1"
          checked-text="是"
          :unchecked-value="0"
          unchecked-text="否"
          v-model="record.isDelay"
          :before-change="handleChangeStatus.bind(null, record, 'isDelay')"
        ></a-switch>
      </template>
      <template #enabled="{ record }">
        <a-switch
          :checked-value="true"
          checked-text="是"
          :unchecked-value="false"
          unchecked-text="否"
          v-model="record.enabled"
          :before-change="handleChangeStatus.bind(null, record, 'enabled')"
        >
        </a-switch>
      </template>
      <template #isRank="{ record }">
        <a-switch
          :checked-value="true"
          checked-text="是"
          :unchecked-value="false"
          unchecked-text="否"
          v-model="record.isRank"
          :before-change="handleChangeStatus.bind(null, record, 'isRank')"
        >
        </a-switch>
      </template>
      <template #label="{ record }">
        <a-space wrap>
          <a-tag bordered v-for="(item, index) in record.label" :key="index">{{ item }}</a-tag>
        </a-space>
      </template>

      <template #allowPushAt="{ record }">
        <a-tag color="arcoblue"> {{ record.allowPushAt }} 秒</a-tag>
      </template>
      <template #delayInterval="{ record }">
        <a-tag color="arcoblue" v-if="record.delayInterval || record.delayInterval == 0">
          {{ record.delayInterval }} 秒</a-tag
        >
        <span v-else>--</span>
      </template>
      <template #expirePushAt="{ record }">
        <a-tag color="arcoblue"> {{ record.expirePushAt }} min</a-tag>
      </template>
      <template #introduce="{ record }">
        <template v-if="record.introduce">
          <a-popover title="群描述">
            <div class="text-overflow-1 w-full overflow-hidden">{{ record.introduce }}</div>
            <template #content>
              <div style="word-break: break-word; white-space: pre-line" class="w-70n">{{ record.introduce }}</div>
            </template>
          </a-popover>
        </template>
        <template v-else>暂未设置</template>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="onAddOrEdit(record)"> 编辑 </a-button>
        <a-button type="text" size="small" @click="onEditSet(record)"> 推送设置 </a-button>
      </template>
    </GiTable>
    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="visible = false" draggable>
      <template #title> 推送设置 </template>
      <div>
        <a-form ref="formRef" :model="form" size="medium" auto-label-width>
          <a-form-item field="allowPushAt" label="允许推送时间(秒)">
            <a-input-number
              v-model="form.allowPushAt"
              :style="{ width: '100px' }"
              placeholder="请输入"
              class="input-demo"
              :min="0"
              :max="100"
            />
          </a-form-item>
          <a-form-item field="expirePushAt" label="过期推送时间(min)">
            <a-input-number
              v-model="form.expirePushAt"
              :style="{ width: '100px' }"
              placeholder="请输入"
              class="input-demo"
              :min="0"
              :max="100"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <EditDrawer ref="EditDrawerRef" @getTableData="getTableData"></EditDrawer>
  </div>
</template>

<script setup>
import { Message } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'
import { sourceChatRoomList, sourceChatRoomCountUpdate, sourceChatRoomCountShow, sourceChatRoomSetDelay } from '@/apis'
// import MsCopyDiv from '@/components/MsCopyDiv/index.vue'
// import { reAssign } from '@/utils/common'
import EditDrawer from './edit.vue'
import ImgHoverPreview from '@/components/ImgHoverPreview/index.vue'

const device = ref()
const is_mobi =
  navigator.userAgent
    .toLowerCase()
    .match(/(ipod|ipad|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|wince)/i) != null
device.value = is_mobi ? 'mobile' : 'pc'

const columns = ref([
  {
    title: '群头像',
    width: 80,
    align: 'center',
    render: (data) => {
      const url = data.record.pic
      return h(ImgHoverPreview, {
        url,
        width: 50
      })
    }
  },
  {
    title: '群名称',
    width: 150,
    align: 'center',
    render: (data) => {
      const text = data.record.name
      return text || '--'
    }
  },
  {
    title: '群得分',
    width: 180,
    dataIndex: 'sort',
    render: ({ record, rowIndex }) => {
      const text1 = `${record.sort}（第${rowIndex + 1}名）`
      const text2 = `${record.sort}（未开启，不参与排名）`
      return record.enabled ? text1 : text2
    },
    align: 'center'
  },
  {
    title: '是否推送',
    width: 120,
    align: 'center',
    slotName: 'isPush'
  },
  {
    title: '是否延时',
    width: 120,
    align: 'center',
    slotName: 'isDelay'
  },
  {
    title: '延时间隔',
    width: 120,
    align: 'center',
    slotName: 'delayInterval'
  },
  {
    title: '是否启用',
    width: 120,
    align: 'center',
    slotName: 'enabled'
  },
  {
    title: '展示图片标签',
    width: 120,
    align: 'center',
    slotName: 'isRank'
  },
  {
    title: '新增排名',
    width: 120,
    dataIndex: 'userAddCountRank',
    align: 'center'
  },
  {
    title: '用户排名',
    width: 120,
    dataIndex: 'userCountRank',
    align: 'center'
  },
  {
    title: '卖货排名',
    width: 120,
    dataIndex: 'gmvRank',
    align: 'center'
  },
  {
    title: '爆品排名',
    width: 120,
    dataIndex: 'hotSaleGoodsCountRank',
    align: 'center'
  },
  // {
  //   title: '群描述',
  //   width: 250,
  //   align: 'center',
  //   slotName: 'introduce'
  // },
  {
    title: '标签',
    width: 180,
    align: 'center',
    slotName: 'label'
  },
  {
    title: '允许推送时间',
    width: 120,
    align: 'center',
    slotName: 'allowPushAt'
  },
  {
    title: '过期推送时间',
    width: 120,
    align: 'center',
    slotName: 'expirePushAt'
  },
  {
    title: '操作',
    width: 140,
    align: 'center',
    fixed: 'right',
    slotName: 'action'
  }
])
const EditDrawerRef = ref()
const loading = ref(false)
const tableData = ref([])
const visible = ref(false)
const itemInfo = ref({})
const { pagination, setTotal } = usePagination(() => getTableData(), {
  defaultPageSize: 100
})
const userCount = reactive({
  sourceChatRoomNum: 0, //群总数
  sourceChatRoomEnablesNum: 0, //启用数量
  sourceChatRoomClosedNum: 0 //关闭数量
})
const listParams = reactive({
  page: 1,
  size: 100,
  isPush: '',
  enabled: '',
  name: ''
})
const form = reactive({
  allowPushAt: '',
  expirePushAt: ''
})
const getCount = async () => {
  const res = await sourceChatRoomCountShow()
  userCount.sourceChatRoomNum = res.data.sourceChatRoomNum
  userCount.sourceChatRoomEnablesNum = res.data.sourceChatRoomEnablesNum
  userCount.sourceChatRoomClosedNum = res.data.sourceChatRoomClosedNum
}
getCount()
const compare = (obj1, obj2) => {
  const val1 = obj1.sort
  const val2 = obj2.sort
  if (val1 < val2) {
    return 1
  } else if (val1 > val2) {
    return -1
  } else {
    return 0
  }
}
// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    const res = await sourceChatRoomList(listParams)
    const openArr = []
    const offArr = []
    res.data.list.forEach((item) => {
      if (item.enabled) {
        openArr.push(item)
      } else {
        offArr.push(item)
      }
    })
    openArr.sort(compare)
    tableData.value = openArr.concat(offArr)
    setTotal(res?.data?.meta?.pagination?.total)
  } finally {
    loading.value = false
  }
}
getTableData()
// // 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}
// 添加/编辑
const onAddOrEdit = (item) => {
  EditDrawerRef.value?.addOrEdit(item)
  // router.push({
  //   path: '/group/groupEdit',
  //   query: {
  //     detailInfo: JSON.stringify(item),
  //     fullPath: route.fullPath
  //   }
  // })
}
const onEditSet = (item) => {
  itemInfo.value = item
  form.allowPushAt = item.allowPushAt
  form.expirePushAt = item.expirePushAt
  /*  allowPushAt: '',
  expirePushAt: '' */
  visible.value = true
}
// 重置筛选查询
const onResetSearch = () => {
  listParams.enabled = listParams.isPush = listParams.name = ''
  changeCurrent(1)
}
// 改变列表中的切换按钮状态
const handleChangeStatus = async (record, str, newValue) => {
  const api = str === 'isDelay' ? sourceChatRoomSetDelay : sourceChatRoomCountUpdate
  const param =
    str === 'isDelay' ? { sourceChatRoomId: record.sourceChatRoomId, [str]: newValue } : { ...record, [str]: newValue }
  await new Promise((resolve, reject) => {
    api(param)
      .then(() => {
        Message.success('操作成功')
        getTableData()
        resolve(true)
      })
      .catch(() => {
        reject()
      })
  })
}
const handleOk = async () => {
  await new Promise((resolve, reject) => {
    sourceChatRoomCountUpdate({
      ...itemInfo.value,
      allowPushAt: form.allowPushAt,
      expirePushAt: form.expirePushAt
    })
      .then(() => {
        Message.success('操作成功')
        getTableData()
        resolve(true)
      })
      .catch(() => {
        reject()
      })
  })
}
</script>

<style lang="scss" scoped>
:deep(.arco-grid) {
  flex-wrap: wrap;
}
:deep(.arco-grid-item) {
  min-width: 250px;
}
:deep(.arco-alert-success) {
  padding: 14px 16px;
  border-color: rgb(var(--success-6));
  background-color: rgba(var(--success-6), 0.08);
  .arco-alert-content {
    color: rgb(var(--success-6));
    font-size: 12px;
  }
}
// :deep(.arco-descriptions-item-value-block) {
//   white-space: nowrap;
// }
:deep(.arco-radio-group .arco-radio) {
  margin-right: 10px;
}
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .btn_wrap {
    dl {
      border-radius: 6px;
      color: #3e3e3e;
    }
    .dl_1 {
      background: #fcedf0;
    }
    .dl_2 {
      background: rgba(232, 249, 240);
      dd {
        color: #0fbf60;
      }
    }
    .dl_3 {
      background: rgba(241, 241, 241);
      dd {
        color: rgba(157, 157, 157);
      }
    }
  }
  .form {
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
}
</style>
